#include "ParseUtil.h"
#include "CryptoUtil.h"
#include <map>
#include <iostream>

using namespace wfrest;
using std::string;
using std::map;
using std::pair;

namespace l
{

    // 从query中解析出2个key对应的2个val
    bool ParseUtil::parse_query_by_key(const HttpReq* req, string& val1, string& val2, const string& key1, const string& key2) {

        if (!req->has_query(key1) || !req->has_query(key2)) {
#ifdef BUG
            std::cout << "BadRequest : query not have " << "key1: " << key1 << " key2: " << key2 << "\n";
#endif
            return false;
        }

        val1 = req->query(key1);
        val2 = req->query(key2);

        return true;

    }

    //从application/x-www-form-urlencoded格式的表单中用两个key解析出两个val
    bool ParseUtil::parse_body_on_form_kv(const HttpReq* req, string& val, const string& key) {

        if (req->content_type() != APPLICATION_URLENCODED) {
#ifdef BUG
            std::cout << "BadRequest content is not APPLICATION_URLENCODED\n";
#endif
            return false;
        }

        //解析key
        map<string, string> formData{ req->form_kv() };

        //如果二者有一个不存在，就算失败，是一个BadRequest
        if (!formData.count(key)) {
#ifdef BUG
            std::cout << "BadRequest : body not have " << "key: " << key << "\n";
#endif
            return false;
        }

        val = formData[key];
        return true;
    }


    //从application/x-www-form-urlencoded格式的表单中用两个key解析出两个val
    bool ParseUtil::parse_body_on_form_kv(const HttpReq* req, string& val1, string& val2, const string& key1, const string& key2) {

        if (req->content_type() != APPLICATION_URLENCODED) {
#ifdef BUG
            std::cout << "BadRequest content is not APPLICATION_URLENCODED\n";
#endif
            return false;
        }

        //解析key1和key2
        map<string, string> formData{ req->form_kv() };

        //如果二者有一个不存在，就算失败，是一个BadRequest
        if (!formData.count(key1) || !formData.count(key2)) {
#ifdef BUG
            std::cout << "BadRequest : body not have " << "key1: " << key1 << " key2: " << key2 << "\n";
#endif
            return false;
        }

        val1 = formData[key1];
        val2 = formData[key2];
        return true;
    }


}//end of namespace l